package com.fingard.dsp.bank.directbank.cib01;

import java.util.Calendar;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/9/20.
 */
public class CIB01Receipt extends CIB01Base implements IReceipt{
    //交易传入的数据
    private String receiptSaveToMainDir = "";

    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        //电子回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt);
                    retAts.respCode = "0";
                    retAts.respInfo = "后台处理中";
                } else {
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                    retAts.respCode = "-1";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public void download(ReqQryReceipt p_reqReceipt) {
        //回单查询返回ATS的对象
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            //按日查询
            while(tmpIntFrom<=tmpIntTo){
                WriteBankLogLn("执行" + tmpIntFrom+"的回单数据查询");
                int intFromStep = tmpIntFrom;//获取起始时间
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//起始时间+1
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));//重新设置起始时间

                //1.1 生成电子回单
                CIB01Header header=new CIB01Header();
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeHeaderReceipt(xmlWriter,header);
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
                xmlWriter.writeStartElement("ELECTRONICRECEIPTTRNRQ");
                xmlWriter.writeElementString("TRNUID",getQryTransID());
                xmlWriter.writeStartElement("RQBODY");
                xmlWriter.writeElementString("RECEIPT_TYPE","01");
                xmlWriter.writeElementString("ACCTID",p_reqReceipt.actNum);
                String date=String.valueOf(intFromStep);
                xmlWriter.writeElementString("RECEIPTDATE",date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6));
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBankReceipt(xmlWriter.toXmlString());

                //测试
                //tmpStrRet[0]="";
                //tmpStrRet[1]="<?xml version=\"1.0\" encoding=\"utf-8\"?><FOX>  <SIGNONMSGSRSV1>    <SONRS>      <STATUS>        <CODE>0</CODE>        <SEVERITY>INFO</SEVERITY>      </STATUS>      <DTSERVER>2017-09-05 10:44:09</DTSERVER>    </SONRS>  </SIGNONMSGSRSV1>  <SECURITIES_MSGSRSV1>    <ELECTRONICRECEIPTTRNRS>      <TRNUID>ewqlectron201709040015</TRNUID>      <STATUS>        <CODE>0</CODE>        <SEVERITY>INFO</SEVERITY>        <MESSAGE>指令提交成功!</MESSAGE>      </STATUS>      <RSBODY>        <ACCTID>117010100100196080</ACCTID>        <CLT_REF_NO>ewqlectron201709040015</CLT_REF_NO>        <STATUS>0</STATUS>      </RSBODY>    </ELECTRONICRECEIPTTRNRS>  </SECURITIES_MSGSRSV1></FOX>\n";

                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                        String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/SEVERITY");
                        if("0".equals(trspcod)){
                            String rspcod = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/ELECTRONICRECEIPTTRNRS/STATUS/CODE");
                            String rspmsg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/ELECTRONICRECEIPTTRNRS/STATUS/MESSAGE");
                            if("0".equals(rspcod)){
                                String status=tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/ELECTRONICRECEIPTTRNRS/RSBODY/STATUS");//处理结果状态
                                if("3".equals(status)){//处理失败，重新发送
                                    WriteBankLogLn("处理失败");
                                }else{
                                    //获取批次号
                                    String cltRefNo=tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/ELECTRONICRECEIPTTRNRS/RSBODY/CLT_REF_NO");
                                    //保存至临时文件中
                                    generateReceiptCodeFile(cltRefNo,"","");
                                    WriteBankLogLn("批次号"+cltRefNo+"回单指令状态(0:未处理，1:处理中，2:已处理)为"+status+",后台定时器处理中");
                                }
                            }else{
                                WriteBankLogLn(rspmsg);
                            }
                        }else{
                            WriteBankLogLn(trspmsg);
                        }
                    }else{
                        WriteBankLogLn(tmpSbMsg.toString());
                    }
                }else{
                    WriteBankLogLn(tmpStrRet[1]);
                }

            }
        }catch (Exception e){
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
        }
    }
}
